package com.cndw.kungfu.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsDayIntKey;
import com.cndw.kungfu.config.ConstantsIntKey;
import com.cndw.kungfu.config.ConstantsLevel;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.QuizQuestion;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.activity.Quiz;
import com.cndw.kungfu.model.activity.QuizManager;
import com.cndw.kungfu.model.sys.ChatMain;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 答题系统
 * 
 * @author lijunhui
 * 
 */
@Controller
public class QuizController {
	@Autowired
	private QuizManager quizManager;

	/**
	 * 开启答题
	 * @param session
	 *  @param type 0日常答题  1灯谜
	 * @return
	 */
	public ResponseMessage openQuiz(Session session, int type) {
		long playerId = session.getUid();
		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		
		if ((type == 1 && player.getLevel() < ConstantsLevel.lv13QuizAtv) || (type == 0 && player.getLevel() < ConstantsLevel.lv13Quiz)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("quiz.openquiz.levellack", ConstantsLevel.lv13Quiz));
		}			
		
		int round = quizManager.getQuizRound(type);
		
		if(round <= 0 || round > ConstantsModel.quizTime.length){
			return ResponseMessage.ticpErrMsg(LanguageLib.get("quiz.openquiz.notquiztime"));
		}

		Quiz quiz = Context.getDataServer().getQuizmap().get(playerId);
		if (quiz != null) {
			int lastReadTime = quiz.getReadQueTime();
			if(lastReadTime < TimeProcesser.getMorningTime() + ConstantsModel.quizTime[round - 1][0] || lastReadTime > TimeProcesser.getMorningTime() + ConstantsModel.quizTime[round - 1][1]){
				// 清除前一轮的quiz
				Context.getDataServer().getQuizmap().remove(playerId);
			}else {
				if (quizManager.finishQuiz(playerId, quiz)) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("quiz.err.finished"));
				} else {
					return ResponseMessage.getSuccMessage(true);
				}
			}
		}
		
		QQDC.getInstance().logClick(player, LogFieldType.quiz);
		
		int quizId = Context.getPlayerServer().getByPlayerId(session.getUid()).getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.quizId);
		if(quizId != round){
			quiz = new Quiz();
			quiz.setLastQueReply(true);
			Context.getDataServer().getQuizmap().put(session.getUid(), quiz);
			Context.getPlayerServer().getByPlayerId(session.getUid()).getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.quizId, round);
			player.getDataInfo().alterExpRet(Constants.expRet_quiz);//参加活动标记
			return ResponseMessage.getSuccMessage(true);
		}else {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("quiz.err.finished"));
		}
	}

	/**
	 * 读取题目
	 * 
	 * @param session
	 *  @param type 0日常答题 1灯谜
	 * @return
	 */
	public ResponseMessage getQuestion(Session session, int type) {
		long playerId = session.getUid();
		Quiz quiz = Context.getDataServer().getQuizmap().get(playerId);
		if (quiz == null) {
			return null;
		}

		if (!quiz.isLastQueReply()) {
			quizManager.dealResult(quiz, false);
		}

		int round = quizManager.getQuizRound(type);
		if(round <= 0 || round > ConstantsModel.quizTime.length){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("over", true);
			return ResponseMessage.getFailMessage(map);
		}

		if (quizManager.finishQuiz(playerId, quiz)) {
			return ResponseMessage.getFailMessage(false);
		}

		int questionDiff = quiz.getRightCount() + quiz.getWrongCount() + 1 < ConstantsModel.quizQuestionNumLimit ? quiz.getRightCount() + quiz.getWrongCount() + 1
				: ConstantsModel.quizQuestionNumLimit;
		quiz.setCurQueId(Context.getCacheCenter().getQuestionByDifficulty(questionDiff, type).getId());
		quiz.setLastQueReply(false);
		
		QuizQuestion curQuestion = Context.getCacheCenter().getQuestionById(quiz.getCurQueId());

		if (curQuestion == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.args"));
		}
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		quiz.setReadQueTime(TimeProcesser.getUnixTime());
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rightCount", quiz.getRightCount());
		map.put("wrongCount", quiz.getWrongCount());
		map.put("integral", player.getDataInfo().intDataGet(ConstantsIntKey.quizScore));
		map.put("rightAnswerCount", quiz.getRightAnswerNum());
		map.put("readQueTime", quiz.getReadQueTime());
		map.put("question", curQuestion.getContent());
		map.put("answer1", curQuestion.getAnswer1());
		map.put("answer2", curQuestion.getAnswer2());
		map.put("answer3", curQuestion.getAnswer3());
		map.put("answer4", curQuestion.getAnswer4());
		
		if(curQuestion.getType() == 0){//日常答题
//			player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.quizItem);
		}
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 回答题目
	 * 
	 * @param session
	 * @param key
	 *            0 使用”正确答案“ 非0 答案
	 * @return
	 */
	public ResponseMessage reply(Session session, int key) {
		long playerId = session.getUid();
		Quiz quiz = Context.getDataServer().getQuizmap().get(playerId);
		if (quiz == null) {
			return null;
		}

		if (quizManager.finishQuiz(playerId, quiz)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("quiz.err.finished"));
		}

		int beginAnswerTime = quiz.getReadQueTime();

		Map<String, Object> map = new HashMap<String, Object>();
		QuizQuestion question = Context.getCacheCenter().getQuestionById(quiz.getCurQueId());
		short rightKey = question.getKey();
		// 超过答题时间
		if (TimeProcesser.getUnixTime() - beginAnswerTime >= ConstantsModel.quizAnswerTimeLimit) {
			quizManager.dealResult(quiz, false);
			map.put("finish", quizManager.finishQuiz(playerId, quiz));
			map.put("key", rightKey);
			map.put("failedType", 0);
			return ResponseMessage.getFailMessage(map);
		}
		if ((key == 0 && quiz.getRightAnswerNum() > 0) || rightKey == key) {
			quizManager.dealResult(quiz, true);
			Player player = Context.getPlayerServer().getByPlayerId(playerId);
			int level = player.getLevel();
			int exp = 0;
			int integral = 0;
			// 计算答题经验
			exp = level > 100 ? 86260 + 300 * (player.getLevel() - 100) : level > 30 ? (int) (0.3 * Math.pow(level, 3) - 31.2 * Math.pow(level, 2) + 1118 * level - 13540) : level + 40;
			
			if(question.getType() == 0){
				exp = exp * 3;
				integral = ConstantsModel.quizRewardIntegral;
			}else if(question.getType() == 1){
				exp =  exp * 6;
			}

			player.alterExp(exp);
			if(integral > 0){
				player.getDataInfo().intDataAlter(ConstantsIntKey.quizScore, integral);
				player.getDataInfo().commitSync();
				Context.getGeneralServer().addTilte(player.getPlayerId(), Constants.titleQuiz, 0);
			}
			player.commitSync();// 提交同步

			map.put("exp", exp);
			map.put("integral", integral);
			boolean finish = quizManager.finishQuiz(playerId, quiz);
			map.put("finish", finish);
			
			LogServer.recordLog(player, ConstantsLog.player, 30008, exp, integral, player.getDataInfo().intDataGet(ConstantsIntKey.quizScore));

			if (key == 0) {
				quiz.setRightAnswerNum(quiz.getRightAnswerNum() - 1);
				map.put("key", rightKey);
				return ResponseMessage.ticpMsg(LanguageLib.get("quiz.reply.useprop", quiz.getRightAnswerNum()), map);
			} else {
				if(finish && question.getType() == 1 && quiz.getRightCount() >= ConstantsModel.quizQuestionNumLimit){//猜对所有灯谜广播
					ChatMain.systemMessage(LanguageLib.get("quiz.activity.allright", player.getPlayerName()));
				}
				return ResponseMessage.getSuccMessage(map);
				//return ResponseMessage.ticpMsg(LanguageLib.get("quiz.reply.answerright"), map);
			}
		} else if (key == 0 && quiz.getRightAnswerNum() <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("quiz.reply.proplack"));
		} else {
			quizManager.dealResult(quiz, false);
			map.put("key", rightKey);
			map.put("finish", quizManager.finishQuiz(playerId, quiz));
			map.put("failedType", 1);
			return ResponseMessage.getFailMessage(map);
		}
	}

	/**
	 * 放弃答题
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage dropQuiz(Session session) {
		long playerId = session.getUid();
		Quiz quiz = Context.getDataServer().getQuizmap().get(playerId);
		if (quiz == null) {
			return null;
		} else {
			Context.getDataServer().getQuizmap().remove(playerId);
		}
		return ResponseMessage.getSuccMessage(true);
	}

	/**
	 * 购买天策
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage bugAnswerProp(Session session) {
		long playerId = session.getUid();
		Quiz quiz = Context.getDataServer().getQuizmap().get(playerId);
		if (quiz == null) {
			return null;
		}

		Player player = Context.getPlayerServer().getByPlayerId(playerId);
		if (player.getGoldAll() < ConstantsModel.quizAnswerPropPrice) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("quiz.buganswerprop.goldlacked"));
		}

		player.alterGoldAll(-ConstantsModel.quizAnswerPropPrice);
		player.commitSync();
		quiz.setRightAnswerNum(quiz.getRightAnswerNum() + ConstantsModel.quizAnswerPropAddNum);

		LogServer.recordLog(player, ConstantsLog.goods, 70005, ConstantsModel.quizAnswerPropPrice, ConstantsModel.quizAnswerPropAddNum);
		//记录消费
		LogServer.costEventLog(playerId, ConstantsModel.quizAnswerPropPrice, ConstantsCost.buyTianCe);
		
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("rightAnswerNum", quiz.getRightAnswerNum());
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());

		return ResponseMessage.getSuccMessage(map);
	}
}
